<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>矿车记录 - 添加/编辑</title>
    <!-- Layui -->
    <link rel="stylesheet" href="../layui/css/layui.css"/>
    <script src="../layui/layui.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Moment.js -->
    <script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
</head>
<body>

<div class="layui-container" style="padding: 20px;">
    <form class="layui-form" id="truckRecordForm" lay-filter="truckRecordForm">
        <input type="hidden" name="id" id="recordId">

        <div class="layui-form-item">
            <label class="layui-form-label">门岗</label>
            <div class="layui-input-block">
                <select name="gateName" id="gateName" lay-verify="required" lay-search>
                    <option value="">请选择门岗</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">施工单位</label>
            <div class="layui-input-block">
                <select name="unitName" id="unitName" lay-verify="required" lay-search>
                    <option value="">请选择单位</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">车牌号</label>
            <div class="layui-input-block">
                <input type="text" name="plate" id="plate" required lay-verify="required|plate" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">时间</label>
            <div class="layui-input-block">
                <input type="text" name="time" id="time" required lay-verify="required" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">材料名称</label>
            <div class="layui-input-block">
                <select name="materialName" id="materialName" lay-verify="required" lay-search>
                    <option value="">请选择材料</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">密度</label>
            <div class="layui-input-block">
                <input type="number" step="0.01" name="density" id="density"
                       readonly placeholder="自动填充" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">体积(m³)</label>
            <div class="layui-input-block">
                <input type="number" step="0.01" name="volume" id="volume"
                       required lay-verify="required" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">重量(吨)</label>
            <div class="layui-input-block">
                <input type="number" step="0.01" name="weight" id="weight"
                       readonly placeholder="自动计算" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">扫描状态</label>
            <div class="layui-input-block">
                <select name="scanStatus" id="scanStatus">
                    <option value="1">已扫描</option>
                    <option value="0">未扫描</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">同步状态</label>
            <div class="layui-input-block">
                <select name="syncStatus" id="syncStatus">
                    <option value="1">已同步</option>
                    <option value="0">未同步</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="submitRecord">提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                <button type="button" class="layui-btn layui-btn-normal" id="backBtn">返回</button>
            </div>
        </div>
    </form>
</div>

<script>
    layui.use(['form', 'layer', 'laydate'], function () {

        // 返回按钮点击事件
        $('#backBtn').on('click', function () {
            window.location.href = 'admin.html#query';
        });

        const form = layui.form;
        const layer = layui.layer;
        const laydate = layui.laydate;

        // 初始化日期控件
        laydate.render({elem: '#time', type: 'datetime'});

        const urlParams = new URLSearchParams(location.search);
        const mode = urlParams.get('mode');
        const recordId = urlParams.get('id');
        let isEditMode = mode === 'edit' && recordId;

        // 动态加载门岗、单位、材料数据
        Promise.all([
            $.get('http://localhost:8080/gate/all'),
            $.get('http://localhost:8080/unit/all'),
            $.get('http://localhost:8080/material/all')
        ]).then(([gatesRes, unitsRes, materialsRes]) => {


            // 加载门岗
            if (gatesRes.code === 0 && gatesRes.data) {
                gatesRes.data.forEach(gate => {
                    $('#gateName').append(`<option value="${gate.gateName}">${gate.gateName}</option>`);
                });
            }

            // 加载单位
            if (unitsRes.code === 200 && unitsRes.data) {
                unitsRes.data.forEach(unit => {
                    $('#unitName').append(`<option value="${unit.unitName}">${unit.unitName}</option>`);
                });
            }

            // 加载材料（改为 select 下拉）
            if (materialsRes.code === 0 && materialsRes.data) {
                materialsRes.data.forEach(material => {
                    $('#materialName').append(
                        `<option value="${material.materialName}" data-density="${material.density}">
                            ${material.materialName}
                         </option>`
                    );
                });

                if (!isEditMode) {
                    // 默认选中第一个门岗
                    if (gatesRes.data.length > 0) {
                        $('#gateName').val(gatesRes.data[0].gateName);
                    }

                    // 默认选中第一个单位
                    if (unitsRes.data.length > 0) {
                        $('#unitName').val(unitsRes.data[0].unitName);
                    }

                    // 已有材料默认选中
                    if (materialsRes.data.length > 0) {
                        const firstMaterial = materialsRes.data[0];
                        $('#materialName').val(firstMaterial.materialName);
                        $('#density').val(firstMaterial.density.toFixed(2));
                    }
                }
            }

            form.render('select');

            // 如果是编辑模式，加载当前记录
            if (isEditMode) {
                $.get(`http://localhost:8080/truck-record/${recordId}`).done(res => {
                    if (res.code === 0 && res.data) {
                        const data = res.data;
                        $('#recordId').val(data.id);
                        $('#gateName').val(data.gateName);
                        $('#unitName').val(data.unitName);
                        $('#plate').val(data.plate);
                        $('#time').val(moment(data.time).format('YYYY-MM-DD HH:mm:ss'));
                        $('#materialName').val(data.materialName);
                        $('#density').val(data.density);
                        $('#volume').val(data.volume);
                        $('#weight').val(data.weight);
                        $('#scanStatus').val(data.scanStatus);
                        $('#syncStatus').val(data.syncStatus);

                        form.render();
                    } else {
                        layer.msg('获取数据失败', {icon: 2});
                        //window.history.back();
                    }
                }).fail(() => {
                    layer.msg('请求失败，请重试', {icon: 2});
                    //window.history.back();
                });
            } else {
                // 非编辑模式下默认填充当前时间
                $('#time').val(moment().format('YYYY-MM-DD HH:mm:ss'));
            }


            form.on('select(materialName)', function(obj) {
                console.log('✅ 材料改变（Layui 事件）', obj);
                const selectedOption = $('#materialName').find('option:selected');
                const density = parseFloat(selectedOption.data('density')) || 0;
                $('#density').val(density.toFixed(2));
                calculateWeight();
            });




            // 体积变化时重新计算重量
            $('#volume').on('input', calculateWeight);

            function calculateWeight() {
                const density = parseFloat($('#density').val()) || 0;
                const volume = parseFloat($('#volume').val()) || 0;
                $('#weight').val((density * volume).toFixed(2));
            }

        }).catch(error => {
            console.error("加载基础数据失败:", error);
            layer.msg("加载基础数据失败，请刷新重试", {icon: 2});
        });


        function generateUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }

        // 提交事件
        form.on('submit(submitRecord)', function (obj) {
            const fields = obj.field;

            // 数据转换
            fields.id = parseInt(fields.id) || undefined;
            fields.density = parseFloat(fields.density) || 0;
            fields.volume = parseFloat(fields.volume) || 0;
            fields.weight = parseFloat(fields.weight) || 0;
            fields.scanStatus = parseInt(fields.scanStatus);
            fields.syncStatus = parseInt(fields.syncStatus);
            fields.uuid = generateUUID();
            const url = isEditMode
                ? `http://localhost:8080/truck-record/${fields.id}`
                : 'http://localhost:8080/truck-record';
            const method = isEditMode ? 'PUT' : 'POST';

            $.ajax({
                url: url,
                method: method,
                contentType: 'application/json',
                data: JSON.stringify(fields),
                success: () => {
                    layer.msg(isEditMode ? '更新成功' : '添加成功');
                    setTimeout(() => {
                        window.location.href = 'admin.html#query';
                    }, 1000);
                },
                error: xhr => {
                    console.error('操作失败:', xhr);
                    layer.msg('操作失败：' + (xhr.responseJSON?.message || xhr.statusText), {icon: 2});
                }
            });

            return false;
        });

        // 自定义表单验证规则
        form.verify({
            plate: function (value) {
                // 车牌号正则（支持新能源、普通车牌）
                const plateRegex = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-DHJ-NP-Z0-9]?$/;
                if (!plateRegex.test(value)) {
                    return '请输入正确的车牌号格式';
                }
            }
        });
    });
</script>

</body>
</html>
